package com.example.controller;

import com.baidu.aip.speech.AipSpeech;
//import com.baidu.aip.speech.AipSpeechResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import org.json.JSONObject;

@RestController
@RequestMapping("/api/speech")
public class SpeechRecognitionController {

    @Autowired
    private AipSpeech aipSpeech;

    @PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> recognizeSpeech(@RequestParam("audio") MultipartFile audioFile) throws IOException {
        // 将音频文件转为字节数组
        byte[] audioData = audioFile.getBytes();

        // 执行语音识别
        JSONObject response = aipSpeech.asr(audioData, "pcm", 16000, null);

        // 检查返回结果中的错误码
        if (response.getInt("err_no") != 0) {
            return ResponseEntity.status(500).body(response.toString());
        }

        // 返回识别结果
        return ResponseEntity.ok(response.toString(4));
    }
}
